import {
    createRouter,
    RouteRecordRaw,
    createWebHashHistory,
    NavigationGuardNext,
} from "vue-router";
import homeChildrenRoutes from "./data"; // 导入 超级管理员 子路由
import usersdata from "./data2"; // 导入 企业账号 子路由
import { loadRoutes } from "./setrouter"; //分配路由

const routes = [
    {
        path: "/",
        component: () => import("../view/system/index.vue"),
        redirect: "/login",
        children: [],
        name: "root",
    },
    {
        path: "/login",
        component: () => import("../view/login/login.vue"),
        name: "login",
    },
];

const router = createRouter({
    history: createWebHashHistory(), //哈希值模式
    routes,
});

// 导航守卫，检查是否已登录并动态加载路由
router.beforeEach(async (to, from, next) => {
    const token = localStorage.getItem("token") || "";
    if (to.name !== 'login' && !token) {
        next({ name: 'login' });
    } else if (token) {
        const userType = localStorage.getItem("userType") || "";
        await loadRoutes(userType); // 等待路由加载

        // 检查是否有匹配的路由
        if (to.matched.length === 0) {
            next({ name: 'login' }); // 或者其他你希望重定向到的路由
        } else {
            next(); // 继续到目标路由
        }
    } else {
        next();
    }
});

export default router;
